﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;


namespace JohnWells.GameLevel
{

    public sealed class Trigger
    {
        public KeyValuePair<string, object>[] Keys;
        public BoundingBox box;

        private bool OnEnterValid;
        private ModelInstance OnEnterTargetModel;
        private ModelInstance OnExitTargetModel;

        public Trigger(Vector3 minPos, Vector3 maxPos, KeyValuePair<string, object>[] keys)
        {
            box = new BoundingBox(minPos, maxPos);
            this.Keys = keys;
            
            OnEnterValid = false;

            OnExitTargetModel = null;
            OnEnterTargetModel = null;
        }

        public void Initialize(Level level)
        {
            foreach (KeyValuePair<string, object> key in Keys)
            {
                if (key.Key.ToLower() == "onexit")
                {
                    OnExitTargetModel = level.GetModel((string)key.Value);
                }

                if (key.Key.ToLower() == "onenter")
                {
                    OnEnterTargetModel = level.GetModel((string)key.Value);
                }
            }
        }

        public void Update (BoundingBox playerBox) {
            if (OnEnterTargetModel != null)
            {
                if (!OnEnterValid && (box.Contains(playerBox) == ContainmentType.Contains))
                {
                    OnEnterValid = true;
                    OnEnterTargetModel.OnEnter();
                }
            }

            if (OnExitTargetModel != null) {

                if (OnEnterValid && !(box.Contains(playerBox) == ContainmentType.Contains))
                {
                    OnEnterValid = false;
                    OnExitTargetModel.OnExit();
                }
            }
        }
    }
}